﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DtuService
{
    class DeviceService : IService
    {
        // key 规则， areaid_deviceid
        private Dictionary<string, Device> deviceDic = new Dictionary<string, Device>();
        public void Init()
        {
            
        }
        public void InsertDevice(string id, Device device)
        {
            if (deviceDic.ContainsKey(id))
            {
                return;
            }
            lock (deviceDic)
            {
                deviceDic.Add(id, device);
            }
        }

        public void RemoveDevice(string key)
        {
            lock (deviceDic)
            {
                if (deviceDic.ContainsKey(key))
                {
                    deviceDic.Remove(key);
                }
            }
        }

        public Device GetDevice(string id) 
        {
            if (deviceDic.ContainsKey(id))
            {
                return deviceDic[id];
            }
            return null;
        }

        public void Tick(float time)
        {
            lock (deviceDic)
            {
                foreach (KeyValuePair<string, Device> device in deviceDic)
                {
                    device.Value.Update(time);
                }
            }
        }

        public void Shutdown()
        {
            foreach (KeyValuePair<string, Device> device in deviceDic)
            {
                device.Value.Shutdown();
            }
            deviceDic.Clear();
        }
    }
}
